package org.liaohailong.library.image.victor;

import android.graphics.Bitmap;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Author: liaohailong
 * Date: 2019/7/14
 * Time: 11:21
 * Description: 缓存管理
 **/
class AvatarCache {
    private static final String TAG = "AvatarCache";

    static final int DEFAULT_MAX_CACHE_SIZE = 1024 * 1024 * 100;

    private String savePath;

    /**
     * 默认100MB硬盘存储空间
     */
    private int maxCacheSize = 1024 * 1024 * 100;

    /**
     * 内存缓存
     */
    private BitmapLruCache bitmapLruCache = new BitmapLruCache();


    void setSavePath(String savePath) {
        // 创建缓存文件夹
        File file = new File(savePath);
        boolean createDirectory = false;
        if (file.exists()) {
            if (file.isDirectory()) {
                this.savePath = savePath;
            } else {
                createDirectory = true;
            }
        } else {
            createDirectory = true;
        }


        if (createDirectory) {
            boolean success;
            if (file.delete()) {
                success = file.mkdirs();
            } else {
                success = false;
            }
            if (success) {
                this.savePath = savePath;
            } else {
                File cacheDir = Avatar.INSTANCE.getContext().getCacheDir();
                this.savePath = cacheDir.getAbsolutePath() + File.separator + TAG;
            }
        }
    }

    void setMaxCacheSize(int maxCacheSize) {
        this.maxCacheSize = maxCacheSize;
    }

    String getFilePath(String url) {
        String body = md5(url);
        return savePath + File.separator + body;
    }

    boolean isCached(String url) {
        String filePath = getFilePath(url);
        Bitmap bitmap = bitmapLruCache.get(filePath);
        return bitmap != null || new File(filePath).exists();
    }

    void saveBitmap(String url, Bitmap bitmap) {
        bitmapLruCache.put(url, bitmap);
    }

    Bitmap getBitmap(String url) {
        return bitmapLruCache.get(url);
    }

    /**
     * 字符串md5
     */
    @NonNull
    private String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
